<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-16
 * Time: 15:08
 */

namespace app\api\controller\v1;


use app\api\model\Coupon as CouponModel;
use app\api\model\CouponUse;
use think\facade\Request;

class Coupon
{
    /**
     * 获取列表
     * @validate('PagingParameter')
     */
    public function getDataListByUse($page,$limit,$coupon_id,$status)
    {
        $where[] = ['coupon_id','eq',$coupon_id];
        if($status) {
            $where[] = ['status','eq',$status];
        }
        $query = CouponUse::where($where)->order('coupon_use.id desc');
        $count = $query->count();
        $result = $query->page($page, $limit)->select()->each(function ($item){
            if($item['status'] == 1) {
                $item['status_name'] = '未使用';
            } else {
                $item['status_name'] = '已使用';
            }
        })->toArray();
        $data['count'] = $count;
        $data['data'] = $result;
        return $data;
    }

    /**
     * 获取列表
     * @validate('PagingParameter')
     */
    public function getDataList($page,$limit,$title)
    {
        $where = [];
        if($title) {
            $where[] = ['title','like','%'.$title.'%'];
        }
        $query = CouponModel::where($where)->order('id desc');
        $count = $query->count();
        $result = $query->page($page, $limit)->select()->toArray();
        $data['count'] = $count;
        $data['data'] = $result;
        return $data;
    }

    /**
     * 获取详情
     * @validate('IdMustBePositiveInt')
     */
    public function getDataInfo($id)
    {
        return CouponModel::get($id);
    }

    /**
     * 创建分类
     * @validate('CheckCoupon')
     */
    public function createData()
    {
        $data = Request::post();
        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);
        CouponModel::create($data);
        return writeJson(201, [], '添加成功！');
    }

    /**
     * 更新信息
     * @validate('CheckCoupon')
     */
    public function updateData()
    {
        $data = Request::put();
        $mode = new CouponModel();
        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);
        $mode->allowField(true)->save($data,['id' => $data['id']]);
        return writeJson(202, [], '修改成功！');
    }

    /**
     * 删除信息
     * @validate('IdMustBePositiveInt')
     */
    public function deleteData($id)
    {
        CouponModel::destroy($id);
        return writeJson(203, [], '删除成功！');
    }
}